import moment from "moment";
import menus from "@/config/menu";
import {IMenu} from "@/common/model/menu";
import _ from 'lodash'
import {BASENAME} from "@/common/constant";

export const API_DATETIME_FMT = "YYYY-MM-DD HH:mm:ss";

export function formatData(dataStr: string) {
  return moment(dataStr).format(API_DATETIME_FMT);
}

export function randomString(length = 8) {
  const str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  let target = "";
  for (let i = 0; i < length; i++) {
    target += str.charAt(Math.round(Math.random() * str.length));
  }
  return target;
}

// 自定义处理DatePicker组件中的时间处理
export function disabledDate(date: moment.Moment) {
  return date && date > moment().endOf("day"); //当天之后日期不可选
}

export function getAuthToken() {
  return localStorage.getItem('X_TOKEN');
}

export function getParameter(key: string) {
  let url = window.location.href.split('?')[1]
  if (!url) {
    return null;
  }
  let arr = url.split('&');
  for (let i in arr) {
    let arr1 = arr[i].split('=')
    if (key === arr1[0]) {
      return arr1[1]
    }
  }
  return null
}

export function getSelectedKey() {
  const selectedKey = window.location.pathname;
  if (selectedKey.indexOf(BASENAME) > -1) {
    return selectedKey.replace(BASENAME, '')
  }
  return selectedKey
}

export function getOpenKeys(currentMenus: IMenu[]) {
  if (_.isEmpty(currentMenus)) {
    return [];
  }
  const openKeys: any = []
  currentMenus.map((menu) => {
    if (menu.routes && menu.routes.length > 0) {
      openKeys.push(menu.path)
    }
  })
  return openKeys
}

export function getCurrentMenus() {
  let currentMenus: IMenu[] = []
  menus.map(item => {
    _getCurrentMenus(item, currentMenus)
  })
  return currentMenus
}

export function _getCurrentMenus(menu: IMenu, currentMenus: IMenu[]) {
  const path = window.location.pathname;
  if (path.indexOf(menu.path) != -1) {
    currentMenus.push(menu)
    if (menu.routes && menu.routes.length > 0) {
      menu.routes.map(r => {
        _getCurrentMenus(r, currentMenus)
      })
    }
  }
}

/**
 * 递归树
 * @param {*} data 文件名
 * @param {*} pid 父级id
 * @param key
 */
export function tree(data: any, pid = 0, key = 'pid') {
  const result = [];
  for (const i in data) {
    if (data[i][key] === pid) {
      const temp = data[i];
      const children = tree(data, data[i].id, key);
      if (children.length) {
        temp.children = children;
      }
      result.push(temp);
    }
  }
  return result;
}
